package service

import (
	"bytes"
	"context"
	"encoding/json"
	"fx_swift_forex/api"
	"fx_swift_forex/pkg/code"
	"fx_swift_forex/pkg/global"
	"fx_swift_forex/pkg/internalerrors"
	"mime/multipart"
)

type ITransferSrv interface {
	// 创建转账
	CreateTransfer(ctx context.Context, req *api.CreateTransferReq) (*api.CreateTransferRes, error)

	// 取消转账
	CancelTransfer(ctx context.Context, req *api.CancelTransferReq) (*api.CancelTransferRes, error)
}
type transferSrv struct {
}

func NewTransferSrv() ITransferSrv {
	return &transferSrv{}
}

// 创建转账
func (t *transferSrv) CreateTransfer(ctx context.Context, req *api.CreateTransferReq) (*api.CreateTransferRes, error) {
	var (
		url  = global.ViperObj.GetString("forex.baseUrl") + "/v2/transfers/create"
		err  error
		body []byte
		obj  *api.CreateTransferRes
	)
	payload := &bytes.Buffer{}
	writer := multipart.NewWriter(payload)
	_ = writer.WriteField("source_account_id", req.SourceAccountId)
	_ = writer.WriteField("destination_account_id", req.DestinationAccountId)
	_ = writer.WriteField("currency", req.Currency)
	_ = writer.WriteField("amount", req.Amount)
	_ = writer.WriteField("reason", req.Reason)
	if err = writer.Close(); err != nil {
		return nil, internalerrors.New(code.ErrUnknown, err.Error())
	}
	body, err = PostRequestToCC(ctx, url, writer.FormDataContentType(), payload)
	if err != nil {
		return nil, internalerrors.New(code.ErrUnknown, err.Error())
	}
	if err = json.Unmarshal(body, &obj); err != nil {
		return nil, internalerrors.New(code.ErrUnknown, err.Error())
	}
	return obj, err
}

// 取消转账
func (t *transferSrv) CancelTransfer(ctx context.Context, req *api.CancelTransferReq) (*api.CancelTransferRes, error) {
	var (
		url     = global.ViperObj.GetString("forex.baseUrl") + "/v2/transfers/"
		usrLast = "/cancel"
		urls    string
		err     error
		body    []byte
		obj     *api.CancelTransferRes
	)
	urls = url + req.Id + usrLast
	payload := &bytes.Buffer{}
	writer := multipart.NewWriter(payload)
	if err = writer.Close(); err != nil {
		return nil, internalerrors.New(code.ErrUnknown, err.Error())
	}
	body, err = PostRequestToCC(ctx, urls, writer.FormDataContentType(), nil)
	if err != nil {
		return nil, internalerrors.New(code.ErrUnknown, err.Error())
	}
	if err = json.Unmarshal(body, &obj); err != nil {
		return nil, internalerrors.New(code.ErrUnknown, err.Error())
	}
	return obj, err
}
